package service.impl;

import dao.BookDao;
import dao.impl.BookDaoImpl;
import pojo.Book;
import pojo.Page;
import service.BookService;

import java.util.List;

/**
 * @author Wxt
 * @create 2022-02-09 20:55
 */
public class BookServiceImpl implements BookService {
    private BookDao bookDao = new BookDaoImpl();
    @Override
    public void addBook(Book book) {
        bookDao.addBook(book);
    }

    @Override
    public void deleteBookById(int id) {
        bookDao.deleteBookById(id);
    }

    @Override
    public void updateBook(Book book) {
        bookDao.updateBook(book);
    }

    @Override
    public Book queryForOneById(int id) {
        return bookDao.queryForOneById(id);
    }

    @Override
    public List<Book> queryAllBooks() {
        return bookDao.queryAllBooks();
    }

    @Override
    public Page<Book> page(int pageNo, int pageSize) {
        Page<Book> page = new Page<>();
        page.setPageSize(pageSize);
        int pageTotalCount = bookDao.queryForPageTotalCount();
        page.setPageCount(pageTotalCount);
        int pageTotal = pageTotalCount / pageSize;
        if(pageTotalCount % pageSize != 0) {
            pageTotal = pageTotal + 1;
        }
        page.setPageTotal(pageTotal);
        if(pageNo < 1) {
            pageNo = 1;
        }
        if(pageNo > page.getPageTotal()) {
            pageNo = page.getPageTotal();
        }
        page.setPageNo(pageNo);
        int begin = (page.getPageNo() - 1) * pageSize;
        List<Book> books = bookDao.queryForItems(begin, pageSize);
        page.setPageItems(books);
        return page;
    }

    @Override
    public Page<Book> pageByPrice(int pageNo, int pageSize, int min, int max) {
        Page<Book> page = new Page<>();
        int pageTotalCount = bookDao.queryForPageTotalCount(min, max);
        page.setPageCount(pageTotalCount);
        int pageTotal = page.getPageCount() / pageSize;
        if(page.getPageCount() % pageSize != 0) {
            pageTotal = pageTotal + 1;
        }
        page.setPageTotal(pageTotal);
        page.setPageNo(pageNo);
        int begin = (page.getPageNo() - 1) * pageSize;
        List<Book> books = bookDao.queryForPageItems(begin, Page.PAGE_SIZE, min, max);
        page.setPageItems(books);
        return page;
    }
}
